package com.eshore.textanalyzer.elk.controller;

import com.alibaba.fastjson.JSONObject;
import com.eshore.textanalyzer.elk.common.EsState;
import com.eshore.textanalyzer.elk.common.HpEsConnect;
import com.eshore.textanalyzer.elk.common.ResponseMessage;
import com.eshore.textanalyzer.elk.pojo.Paper;
import com.eshore.textanalyzer.elk.pojo.TagEsState;
import com.eshore.textanalyzer.elk.pojo.TagHotwords;
import com.eshore.textanalyzer.elk.pojo.ToEsData;
import com.eshore.textanalyzer.elk.service.ElkService;
import com.eshore.textanalyzer.elk.service.HotwordsService;
import com.eshore.textanalyzer.elk.service.TagEsStateService;
import com.sun.xml.internal.xsom.XSUnionSimpleType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @authr xyd
 * @date 2021/5/11
 * 编写hp_big_data
 * elk操作接口
 */
@Slf4j
@CrossOrigin
@RestController
@Api(value = "黄埔热线分析接口",tags = "黄埔热线分析接口")
@RequestMapping("/hp")
public class HpElkController {

    @Autowired
    @Qualifier(value = "HpElkServiceImpl")
    private ElkService elkService;

    @Autowired
    @Qualifier(value = "HpElkServiceImpl")
    private HotwordsService hotwordsService;

    @Autowired
    private TagEsStateService tagEsStateService;

    /**
     * 批量从mysql ===> es
     * 按月导数 -- 需加入月份条件
     * @return
     */
//    @PostMapping(value = "hpLoadDataToEs",produces = "application/json;charset=utf-8")
//    public ResponseMessage hpLoadDataToEs() {
//        // 封装数据库连接信息
//        ToEsData toEsData = new ToEsData();
//        toEsData.setUrl("jdbc:mysql://127.0.0.1:3316/hp-bigdata-test?useUnicode=true&characterEncoding=utf-8");
//        toEsData.setUserName("root");
//        toEsData.setPassword("UfajV:4bCd>6");
//        toEsData.setClassName("com.mysql.cj.jdbc.Driver");
//        toEsData.setIndexName("hpdata");
//        // 调用执行
//        try {
//            String uuid = UUID.randomUUID().toString().replaceAll("-","");
//            TagEsState tagEsState = new TagEsState();
//            tagEsState.setId(uuid);
//            tagEsState.setBusinessType("");
//            tagEsStateService.insertState(tagEsState);
//            ResponseMessage res = elkService.writeMysqlDataToEs(toEsData,tagEsState);
//            return res;
//        }catch (SQLException e) {
//            e.printStackTrace();
//            return ResponseMessage.createByError("数据导入到es出错，请检查");
//        }
//    }

    /**
     * 重新加载es数据
     * 先清空es hpdata数据
     * ---> 全量加载all  ---> 按照月份加载
     * 成功：则执行导数 mysql -> es
     * 失败：记录入库
     * @param business_type 业务类型、用月份表示 yyyy-mm/all
     * @return
     */
    @ApiOperation(value = "重载es数据",
            notes = "传递business_type来加载，月份(yyyy-MM)或者'all'来重新加载数据，如果已经有正在加载得流程，" +
                    "则提示该流程正在执行，重新加载之前会按照条件先清空es中数据")
    @ApiImplicitParam(name = "business_type",value = "导数流程类型，yyyy-MM或者all表示全量",required = true,dataType = "String")
    @PostMapping(value = "hpOverloadingData")
    public ResponseMessage hpOverloadingData(String business_type) {
        // 这里判断是否可以执行 business_type executing_state判断
        List<TagEsState> list = tagEsStateService.checkoutState(business_type);
        if (list.size() == 0) {
            ToEsData toEsData = new ToEsData();
            toEsData.setUrl(HpEsConnect.URL);
            toEsData.setUserName(HpEsConnect.USER_NAME);
            toEsData.setPassword(HpEsConnect.PASSWORD);
            toEsData.setClassName(HpEsConnect.CLASS_NAME);
            toEsData.setIndexName(HpEsConnect.INDEX_NAME);
            // 这里根据 business_type 来做全量、月份(增量)导数
            switch (business_type) {
                case "all":
                    toEsData.setSql("select * from tag_rx_order");
                    break;
                default:
                    String sql = "select * from tag_rx_order where create_time_month_1='" + business_type + "'";
                    toEsData.setSql(sql);
            }
            // 新增一条状态记录
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            TagEsState tagEsState = new TagEsState();
            tagEsState.setId(uuid);
            tagEsState.setBusinessType(business_type);
            tagEsStateService.insertState(tagEsState);
            // 执行清空数据 状态抽查 根据business_type来执行相应的清空
            elkService.clearEsIndexData(HpEsConnect.INDEX_NAME, business_type,tagEsState);
            try {
                ResponseMessage result = elkService.writeMysqlDataToEs(toEsData,tagEsState);
                return result;
            } catch (SQLException e) {
                e.printStackTrace();
                // 这里做日志状态更新
                //获取当前结束的日期
                String end_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                tagEsState.setEndTime(end_time);
                tagEsState.setMsg(e.getMessage());
                tagEsState.setExecutingState(EsState.FAILED);
                tagEsStateService.updateState(tagEsState);
                return ResponseMessage.createByError("重载数据失败");
            }
        } else {
            return ResponseMessage.createBySuccess(business_type+"任务已经正在执行",list);
        }
    }

    /**
     * 热词分析代码
     * @param time_month 月份 yyyy-MM
     */
    @ApiOperation(value = "加载热词数据",
            notes = "异步请求，传递time_month从es中加载当月热词数据并入库，time_month月份(yyyy-MM)，会先根据月份删除指定的月份热词信息再进行更新入库")
    @ApiImplicitParam(name = "time_month",value = "当前月份热词",required = true,dataType = "String")
    @Async("taskExecutor")
    @PostMapping("/hpHotWordsByMonth")
    public ResponseMessage hpHotWordsByMonth(String time_month){
        log.info("获取===" + time_month + "===月份的热词分析数据");
        ResponseMessage res = elkService.getHotWordsByMonth(time_month);
        if (res.getStatus() == 200) {
            Map<String,Long> dataMap = JSONObject.parseObject(JSONObject.toJSONString(res.getData()), Map.class);
            // code 插入条数 大于等于0
            int code = hotwordsService.insertBatch(dataMap,time_month);
            return ResponseMessage.createBySuccess(code);
        } else {
            // 执行失败
            return res;
        }
    }

    /**
     * 根据月份
     * 获取热词信息
     * @param time_month
     * @return
     */
    @ApiOperation(value = "获取热词统计信息",
            notes = "根据time_month月份(yyyy-MM)从应用库中获取热词数据")
    @ApiImplicitParam(name = "time_month",value = "当前月份",required = true,dataType = "String")
    @GetMapping("/getHotwords")
    public ResponseMessage getHotwords(String time_month) {
        List<TagHotwords> hotwordsList = hotwordsService.getHotwords(time_month);
        return ResponseMessage.createBySuccess(hotwordsList);
    }

    /**
     * 根据热词
     * 获取文本分析 工单详情
     * 分页 default 1-10
     * @param page
     * @param size
     * @param texts
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "工单详情文本分析",
            notes = "根据texts热词从es中查询包含该热词的工单，texts是es统计的热词信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int"),
            @ApiImplicitParam(name = "size",value = "每页条数",required = true,dataType = "int"),
            @ApiImplicitParam(name = "texts",value = "热词信息",required = true,dataType = "String")
    })
    @PostMapping("/getEsDataListHp")
    public ResponseMessage getEsDataListHp(int page, int size, String texts) throws IOException {
        ResponseMessage listHp = elkService.getEsDataListHp(page,size,texts);
        return listHp;
    }
}
